define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'shops/play/index' + location.search,
                    add_url: 'shops/play/add',
                    edit_url: 'shops/play/edit',
                    // del_url: 'shops/play/del',
                    multi_url: 'shops/play/multi',
                    import_url: 'shops/play/import',
                    table: 'play',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                search:false,
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible:true,
                escape:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'shop.shop_name', title: '店铺信息', operate: 'LIKE', align: 'left',halign:"center"},
                        {field: 'phone', title: '商家号码'},
                        {field: 'channel', title: '分发渠道', searchList: Config.channelList,visible:false},
                        {field: 'parent_play_no', title: '是否是循环活动', searchList: {"否":"否","是":"是"}, operate: false, formatter: Table.api.formatter.status},
                        {field: 'virtual_num', title: '分发状态', searchList: {"已分发":"已分发","无法分发":"无法分发","未分发":"未分发","无法分发已处理":"无法分发已处理"}, align: 'left',halign:"center"},
                        {field: 'play_status', searchList: {"1":"待审核","2":"进行中","3":"待支付","4":"已结束","5":"已完成",'6':'驳回'}, title: '活动状态', formatter: Table.api.formatter.status},
                        {field: 'shop_type', searchList: {"1":"美团","2":"饿了么","3":"京东"}, title: '活动平台', formatter: Table.api.formatter.status},
                        {field: 'pay_status', searchList: {"0":"待支付","1":"部分支付","2":"已支付","3":"已冻结"}, title: '支付状态', formatter: Table.api.formatter.status},
                        {field: 'play_type', searchList: {"1":"霸王餐","2":"返利餐"}, title: '活动类型', formatter: Table.api.formatter.status},
                        // {field: 'total_money', title: '金额',operate:false},
                        {field: 'service_amt', title: '服务费',operate:false, align: 'left',halign:"center"},
                        // {field: 'no_feedback', title: '返点',  formatter: Table.api.formatter.normal},
                        {field: 'stock_text', title: '活动名额（剩余/全部）', formatter: Table.api.formatter.normal,operate:false, align: 'left',halign:"center"},
                        {field: 'back_money_text', title: '优惠条件',operate:false},
                        {field: 'scheme_no', searchList: {"1":"用餐反馈","2":"图文反馈","3":"无需反馈"}, title: '活动方案', formatter: Table.api.formatter.status},
                        {field: 'play_label', searchList: {"0":"正常活动","1":"大牌专享","2":"新用户专享"}, title: '活动标签', formatter: Table.api.formatter.status},
                        {field: 'end_time_str', title: '活动日期', addclass:'datetimerange'},
                        // {field: 'end_date', title: '结束日期', formatter: Table.api.formatter.datetime},
                        {field: 'start_time_str', title: '时间段',operate:false},
                        {field: 'total_pay', title: '待上传',operate:false},
                        {field: 'total_service_amt', title: '待审核',operate:false},
                        {field: 'acture_pay', title: '已完成',operate:false},
                        {field: 'service_admin_by', title: '所属业务员',searchList: Config.salesmanList},
                        {field: 'is_pay', searchList: {"0":"后台发布","1":"前台余额支付"}, title: '活动方式', formatter: Table.api.formatter.status},
                        {field: 'shop.address', title: '店铺定位', operate: 'LIKE', align: 'left',halign:"center"},
                        {field: 'last_pay_time', title: '支付时间',operate:false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'create_dt', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'update_dt', title: __('Updatetime'),operate:false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', 
                        title: __('Operate'), 
                        table: table, 
                        events: Table.api.events.operate, 
                        buttons: [{
                            name: "agree",
                            title: "审核通过",
                            classname: "btn btn-xs btn-success btn-magic btn-ajax",
                            icon: "fa fa-check",
                            text: "同意",
                            confirm: "确认点击同意，通过审核？",
                            url: "shops/play/agree",
                            visible: function(row){
                                if (1 == row.play_status) return ! 0
                            }, 
                            refresh: true
                        },
                        {
                            name: "refuse",
                            title: __("审核不通过"),
                            classname: "btn btn-xs btn-danger btn-dialog",
                            icon: "fa fa-times",
                            text: "拒绝",
                            url: "shops/play/refuse",
                            extend: 'data-area=["500px","270px"]',
                            visible: function(row){
                                if (1 == row.play_status) return ! 0
                            }, 
                            refresh: true,
                        },
                        {
                            name: "edit",
                            text: __("编辑"),
                            classname: "btn btn-xs btn-success btn-dialog",
                            icon: "fa fa-pencil",
                            url: "shops/play/edit",
                            refresh: true,
                        },
                        {
                            name: 'copy',
                            text: '复制活动',
                            icon: 'fa',
                            classname: 'btn btn-xs btn-info btn-dialog',
                            url: 'shops/play/copy',
                            refresh: true,
                        },
                        {
                            name: "end",
                            title: "结束活动",
                            classname: "btn btn-xs btn-danger btn-magic btn-ajax",
                            icon: "fa",
                            text: "结束活动",
                            confirm: "确认点击结束活动？",
                            url: "shops/play/end",
                            visible: function(row){
                                if (2 == row.play_status) return ! 0
                            }, 
                            refresh: true
                        },
                        // {
                        //     name: "order",
                        //     classname: "btn btn-xs btn-primary btn-dialog",
                        //     icon: "fa fa-eye",
                        //     text: "订单列表",
                        //     url: "shops/play/order",
                        // },
                        ],
                        formatter: Table.api.formatter.operate}
                    ]
                ]
            });
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'shops/play/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                search:false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'shop_name', title: __('Name'), align: 'left'},
                        {
                            field: 'delete_dt',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'shops/play/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'shops/play/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        order: function () {
            var ids = $("#assign-data-ids").val();

            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'shops/play/order/ids/' + ids,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'user.nickname', title: '用户名', operate: 'LIKE'},
                        {field: 'shop.shop_name', title: '店铺名称', operate: 'LIKE'},
                        {field: 'shop.shop_type_text', title: '下单平台', operate: 'LIKE'},
                        {field: 'back_money_text', title: '优惠条件'},
                        {field: 'service_amt', title: '服务费'},
                        {field: 'scheme_no_text', title: '活动方案', operate: 'LIKE'},
                        {field: 'order.wm_order_sn', title: '外卖单号', operate: 'LIKE'},
                        {field: 'order.place_time', title: '抢单时间', operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'order.order_status', title: __('Status'), searchList: {"1":"待上传","2":"待审核","3":"已完成","6":"待商家复审","-1":"已取消","-2":"超时取消","-3":"已拒绝",'-5':'不满意反馈','-6':'不满意通过','-7':'异常订单','-8':'异常订单（客服已处理）','-9':'异常订单（已完成）','-4':'异常订单（已取消）'}, formatter: Table.api.formatter.status},
                        {field: 'proof.one_image_url', title: '订单截图1', operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'proof.two_image_url', title: '订单截图2', operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'proof.three_image_url', title: '订单截图3', operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'order.create_dt', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'order.update_dt', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', 
                        title: __('Operate'), 
                        table: table, 
                        events: Table.api.events.operate,
                        buttons: [
                            {
                                name: "edit",
                                text: __("订单详情"),
                                classname: "btn btn-xs btn-info btn-dialog",
                                icon: "fa fa-eye",
                                url: "order/order/edit"
                            },
                        ],
                        formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        copy: function () {
            Controller.api.bindevent();
            $('#c-shop_no').change(function () {
                var shop_no = $('#c-shop_no').val();
                $.ajax({
                    url:"/hFtNsJROTk.php/shops/play/nopay",
                    data: { shop_no: shop_no },
                    success:function(result){
                        $('#nopay').val(result.data.nopay)
                        $('#c-address').val(result.data.address)
                        $('#c-shop_type').val(result.data.shop_type)
                        $('#c-service_amt').val(result.data.service_amt)
                        var html = '';
                        for (var i = 0; i <= result.data.qrcode.length - 1; i++) {
                            html+='<li class="col-xs-3"><a href="" data-url="" target="_blank" class="thumbnail"><img src="'+result.data.domain+result.data.qrcode[i]+'" class="img-responsive"></a></li>'
                        }
                        $('#c-qrcode').html(html)
                        $('#channel').attr('data-serviceamt',result.data.shop_serviceamt)
                        var serviceamt = $('#channel').attr('data-serviceamt')
                        serviceamt = JSON.parse(serviceamt)
                        if (parseInt($('#c-user_pay').val())>0 && parseInt($('#c-shop_settlement').val())>0) {
                            var mf = ''
                            for (var i = serviceamt.length - 1; i >= 0; i--) {
                                if (serviceamt[i].channel_name=='吃喝不愁') {
                                    var f=parseInt($('#c-user_pay').val())-serviceamt[i].service_amt
                                    mf='满'+parseInt($('#c-user_pay').val())+'返'+f
                                }
                            }
                            console.log(mf)
                            $('#channel .flex').find('input').eq(0).val(mf)
                        }
                    }
                })
            })

        },

        add: function () {
            Controller.api.bindevent();
            $('#c-shop_no').change(function () {
                var shop_no = $('#c-shop_no').val();
                $.ajax({
                    url:"/hFtNsJROTk.php/shops/play/nopay",
                    data: { shop_no: shop_no },
                    success:function(result){
                        $('#nopay').val(result.data.nopay)
                        $('#c-address').val(result.data.address)
                        $('#c-shop_type').val(result.data.shop_type)
                        $('#c-service_amt').val(result.data.service_amt)
                        var html = '';
                        for (var i = 0; i <= result.data.qrcode.length - 1; i++) {
                            html+='<li class="col-xs-3"><a href="" data-url="" target="_blank" class="thumbnail"><img src="'+result.data.domain+result.data.qrcode[i]+'" class="img-responsive"></a></li>'
                        }
                        $('#c-qrcode').html(html)
                        $('#channel').attr('data-serviceamt',result.data.shop_serviceamt)
                        var serviceamt = $('#channel').attr('data-serviceamt')
                        serviceamt = JSON.parse(serviceamt)
                        if (parseInt($('#c-user_pay').val())>0 && parseInt($('#c-shop_settlement').val())>0) {
                            var mf = ''
                            for (var i = serviceamt.length - 1; i >= 0; i--) {
                                if (serviceamt[i].channel_name=='吃喝不愁') {
                                    var f=parseInt($('#c-user_pay').val())-serviceamt[i].service_amt
                                    mf='满'+parseInt($('#c-user_pay').val())+'返'+f
                                }
                            }
                            console.log(mf)
                            $('#channel .flex').find('input').eq(0).val(mf)
                        }
                        console.log(result.data.firstRelease)
                        $('#append p').each(function (i,j) {
                            var name=$(j).data('id')
                            $(j).attr('data-firstRelease',result.data.firstRelease[name])
                        })
                    }
                })
            })
        },
        edit: function () {
            Controller.api.bindevent();
        },
        refuse: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                $(document).on("change", "input[name='row[times_limit]']", function(e){
                    var val = $("input[name='row[times_limit]']:checked").val();
                    if (val==1) {
                        $('#xdcs').show();
                    } else {
                        $('#xdcs').hide();
                    }
                });
                $(document).on("change", "#c-play_type", function(e){
                    var val = $("#c-play_type").val();
                    if (val==2) {
                        $('#is_qcsc').show();
                        $('#user_pay').hide();
                    } else {
                        $('#is_qcsc').hide();
                        $('#user_pay').show();
                    }
                });
            }
        }
    };
    return Controller;
});
